import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:netflix_social/constants/app_constants.dart';
import 'package:netflix_social/models/video.dart';
import 'package:netflix_social/providers/video_provider.dart';
import 'package:netflix_social/theme/app_theme.dart';
import 'package:netflix_social/widgets/content_row.dart';
import 'package:netflix_social/widgets/hero_content.dart';
import 'package:provider/provider.dart';

class HomeTab extends StatefulWidget {
  const HomeTab({Key? key}) : super(key: key);

  @override
  State<HomeTab> createState() => _HomeTabState();
}

class _HomeTabState extends State<HomeTab> {
  final _scrollController = ScrollController();
  bool _isScrolled = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    if (_scrollController.offset > 20 && !_isScrolled) {
      setState(() {
        _isScrolled = true;
      });
    } else if (_scrollController.offset <= 20 && _isScrolled) {
      setState(() {
        _isScrolled = false;
      });
    }
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppTheme.backgroundColor,
      body: Consumer<VideoProvider>(
        builder: (context, videoProvider, child) {
          if (videoProvider.isLoading) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(AppTheme.netflixRed),
              ),
            );
          }

          // 获取特色内容（第一个视频）
          final featuredVideo = videoProvider.videos.isNotEmpty
              ? videoProvider.videos.first
              : null;

          return Stack(
            children: [
              // 内容
              CustomScrollView(
                controller: _scrollController,
                slivers: [
                  // 添加空白安全区域
                  const SliverToBoxAdapter(
                    child: SizedBox(height: kToolbarHeight + 20),
                  ),
                  // 英雄区/特色内容
                  if (featuredVideo != null)
                    SliverToBoxAdapter(
                      child: HeroContent(video: featuredVideo),
                    ),
                  // 继续观看
                  if (videoProvider.continueWatching.isNotEmpty)
                    SliverToBoxAdapter(
                      child: ContentRow(
                        title: '继续观看',
                        videos: videoProvider.continueWatching,
                        showProgress: true,
                      ),
                    ),
                  // 好友正在看
                  SliverToBoxAdapter(
                    child: ContentRow(
                      title: '好友正在看',
                      videos: videoProvider.videos.take(3).toList(),
                      showFriendAvatar: true,
                    ),
                  ),
                  // 热门推荐
                  SliverToBoxAdapter(
                    child: ContentRow(
                      title: '热门推荐',
                      videos: videoProvider.trending.take(5).toList(),
                      showRank: true,
                    ),
                  ),
                  // 为你推荐
                  SliverToBoxAdapter(
                    child: ContentRow(
                      title: '为你推荐',
                      videos: videoProvider.recommended.take(5).toList(),
                    ),
                  ),
                  // 底部空白
                  const SliverToBoxAdapter(
                    child: SizedBox(height: 20),
                  ),
                ],
              ),
              // 顶部导航栏
              Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Container(
                  padding: EdgeInsets.only(
                    top: MediaQuery.of(context).padding.top,
                    left: 16,
                    right: 16,
                    bottom: 16,
                  ),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      colors: [
                        Colors.black.withOpacity(_isScrolled ? 0.8 : 0.6),
                        Colors.black.withOpacity(_isScrolled ? 0.6 : 0.0),
                      ],
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        AppConstants.appName,
                        style: const TextStyle(
                          color: AppTheme.netflixRed,
                          fontSize: 22,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Row(
                        children: [
                          IconButton(
                            icon: const Icon(Icons.notifications_none),
                            color: Colors.white,
                            onPressed: () {
                              Navigator.pushNamed(
                                context,
                                AppConstants.notificationsRoute,
                              );
                            },
                          ),
                          IconButton(
                            icon: const Icon(Icons.search),
                            color: Colors.white,
                            onPressed: () {
                              Navigator.pushNamed(
                                context,
                                AppConstants.searchRoute,
                              );
                            },
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }
}
